package com.hjm.project.ActActive.ActActive.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.Utils;
import com.hjm.project.ActActivationReturn.ActActivationReturn.service.IActActivationReturnService;
import com.hjm.project.ActActivityDistribution.ActActivityDistribution.service.IActActivityDistributionService;
import com.hjm.project.ActPaymentType.ActPaymentType.service.IActPaymentTypeService;
import com.hjm.project.ActStage.ActStage.service.IActStageService;
import com.hjm.project.ActTerminalModel.ActTerminalModel.service.IActTerminalModelService;
import com.hjm.project.actTransactionCompliance.compliance.service.IActTransactionComplianceService;
import com.hjm.project.terminal.manufacturer.service.IManufacturerService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.project.ActActive.ActActive.domain.ActActive;
import com.hjm.project.ActActive.ActActive.service.IActActiveService;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.framework.web.page.TableDataInfo;

/**
 * 活动配置Controller
 *
 * @author LOVE
 * @date 2020-11-28
 */
@Controller
@RequestMapping("/ActActive/ActActive")
public class ActActiveController extends BaseController
{
    private String prefix = "ActActive/ActActive";

    @Autowired
    private IActActiveService actActiveService;

    @Autowired
    private IManufacturerService manufacturerService;

    @Autowired
    private IActActivationReturnService iActActivationReturnService;

    @Autowired
    private IActTransactionComplianceService iActTransactionComplianceService;

    @Autowired
    private IActStageService iActStageService;


    @Autowired
    private IActPaymentTypeService iActPaymentTypeService;

    @Autowired
    private IActActivityDistributionService iActActivityDistributionService;



    @Autowired
    private IActTerminalModelService actTerminalModelService;

    @RequiresPermissions("ActActive:ActActive:view")
    @GetMapping()
    public String ActActive()
    {
        return prefix + "/ActActive";
    }

    /**
     * 查询活动配置列表
     */
    @RequiresPermissions("ActActive:ActActive:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ActActive actActive) {
        startPage();
        List<ActActive> list = actActiveService.selectActActiveList(actActive);
        return getDataTable(list);
    }

    /**
     * 导出活动配置列表
     */
    @RequiresPermissions("ActActive:ActActive:export")
    @Log(title = "活动配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ActActive actActive)
    {
        List<ActActive> list = actActiveService.selectActActiveList(actActive);
        ExcelUtil<ActActive> util = new ExcelUtil<ActActive>(ActActive.class);
        return util.exportExcel(list, "ActActive");
    }

    @RequestMapping("add")
    public String add(ModelMap mmap , @RequestParam Map map) {
        try {
            mmap.put("update", map.get("update"));
            mmap.put("act_id", map.get("act_id"));
            mmap.put("manufacturer", manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null));
            if (Utils.IsNull(map.get("update"))) {
                List<Map<String, Object>> actTerminalModel = new ArrayList<>();
                Map maps = new HashMap();
                actTerminalModel.add(maps);
                mmap.put("actTerminalModel", actTerminalModel);
            } else {
                //修改终端活动 - 根据活动ID查询当前活动信息
                Map<String, Object> actActive = actActiveService.getActActive(map);
                mmap.put("actActive", actActive);
                //查询活动终端匹配表
                List<Map<String, Object>> actTerminalModel = actTerminalModelService.getActTerminalModel(map);
                //活动终端匹配表数据处理
                for (Map<String, Object> item : actTerminalModel) {
                    //活动终端匹配表 终端型号ID
                    item.put("term_num", item.get("TERMINAL_MODEL_ID"));
                    //获取终端厂商表数据
                    Map<String, Object> actManufacturer = manufacturerService.getActManufacturer(item);
                    item.put("manu_num", actManufacturer.get("MANU_CODE"));

                    List<Map<String, Object>> terminalModel = manufacturerService.getTerminalModel(item);
                    item.put("terminalModel", terminalModel);
                }
                mmap.put("actTerminalModel", actTerminalModel);

            }
        } catch (Exception e) {
            throw new BusinessException("打开分润低价规则模板列表");
        }
        return prefix + "/add";
    }

    /**
     * 新增保存活动配置
     */
    @RequiresPermissions("ActActive:ActActive:add")
    @Log(title = "活动配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ActActive actActive)
    {
        return toAjax(actActiveService.insertActActive(actActive));
    }

    /**
     * 修改活动配置
     */
    @GetMapping("/edit/{actId}")
    public String edit(@PathVariable("actId") String actId, ModelMap mmap)
    {
        ActActive actActive = actActiveService.selectActActiveById(actId);
        mmap.put("actActive", actActive);
        return prefix + "/edit";
    }

    /**
     * 修改保存活动配置
     */
    @RequiresPermissions("ActActive:ActActive:edit")
    @Log(title = "活动配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ActActive actActive)
    {
        return toAjax(actActiveService.updateActActive(actActive));
    }

    /**
     * 删除活动配置
     */
    @RequiresPermissions("ActActive:ActActive:remove")
    @Log(title = "活动配置", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int result=actActiveService.deleteActActiveByIds(ids);
        if (result==-1){
            return AjaxResult.error("该活动已绑定机具！");
        }
        if (result==-2){
            return AjaxResult.error("该活动已删除！");
        }
        return toAjax(result);
    }

    /**
     * 查询活动配置列表
     */
    /*@PostMapping("/actList")
    @ResponseBody
   *//* public TableDataInfo actList(ActActive actActive)
    {
        startPage();
        *//**//*List<ActActive> list = actActiveService.getActByAgent(actActive);*//**//*
        return null;
        return getDataTable(list);
    }*/


    @RequestMapping("/getTerminalModel")
    public @ResponseBody
    List<Map<String, String>> getTerminalModel(@RequestParam Map params) throws Exception {
        List<Map<String, Object>> terminalModel = manufacturerService.getTerminalModel(params);
        List<Map<String, String>> list = new ArrayList<>();
        for (Map<String, Object> item : terminalModel) {
            Map<String, String> map = new HashMap<>();
            map.put("value", String.valueOf(item.get("ID")));
            map.put("label", String.valueOf(item.get("MODEL")));
            System.out.println(map);
            list.add(map);
        }
        return list;
    }



    @RequestMapping("/getCs")
    public @ResponseBody
    List<Map> getCs() throws Exception {

        return manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null);
    }


    @RequestMapping("/getZd")
    public @ResponseBody
    List<Map> getZd(@RequestParam Map map) throws Exception {

        return manufacturerService.getTerminalModel(map);
    }


    /**
     * 新增活动保存
     *
     * @return
     */
    @Transactional
    @RequestMapping("/saveActActive")
    public @ResponseBody AjaxResult saveActActive(@RequestParam Map map,@RequestParam List<String> source,@RequestParam List<String> terminal_model_id, String id) throws  Exception {
        boolean flage = true;
        if (Utils.IsNull(map.get("update"))) {
            int act_id = actActiveService.getNextval();
            map.put("createname", this.getLoginName());
            map.put("act_id", act_id);
            List<Map<String, Object>> list = new ArrayList<>();
            if (terminal_model_id.size()<=0){
                return AjaxResult.error("终端型号必选");
            }
            if (!Utils.IsNull(terminal_model_id) && terminal_model_id.size()>0 ) {
                for (int i = 0; i < terminal_model_id.size(); i++) {
                    if(StringUtils.isBlank(terminal_model_id.get(i))){
                        return AjaxResult.error("终端型号必选");
                    }
                    Map<String, Object> maps = new HashMap<>();
                    maps.put("terminal_model_id", terminal_model_id.get(i));
                    maps.put("act_id", act_id);
                    maps.put("source", source.get(i));
                    list.add(maps);
                }

            }
            if (actActiveService.addActActive(map)) {
                if (list.size() > 0) {
                    //批量添加新增的活动匹配终端
                    flage = actTerminalModelService.batchInsertActTerminalModel(list);
                }
            }
            if (flage) {
                return toAjax(1);
            }
        } else {
            String act_id = String.valueOf(map.get("act_id"));
            if (actActiveService.updateActActives(map)) {
                List<Map<String, Object>> list = new ArrayList<>();
                if (!Utils.IsNull(terminal_model_id)) {
                    if (!Utils.IsNull(id)) {
                        //存在需要修改的 活动匹配终端
                        Map<String, Object> maps = new HashMap<>();
                        maps.put("terminal_model_id", terminal_model_id);
                        maps.put("source", source);
                        maps.put("act_id", act_id);
                        maps.put("id", id);
                        if (!actTerminalModelService.updateActTerminalModels(map)) {
                            flage = false;
                        }
                    } else {
                        //存在需要新增的 活动匹配终端
                        Map<String, Object> maps1 = new HashMap<>();
                        maps1.put("terminal_model_id", terminal_model_id);
                        maps1.put("act_id", act_id);
                        maps1.put("source", source);
                        list.add(maps1);
                    }
                }
                if (list.size() > 0) {

                    //批量添加新增的活动匹配终端
                    flage = actTerminalModelService.batchInsertActTerminalModel(list);
                }
            }
            if (flage) {
                return toAjax(1);
            }
        }
        return  error("操作失败");
    }

    /**
     * 配置活动返现规则
     */
    @GetMapping("/dbfx")
    public String dbfx(ModelMap map ,@RequestParam Map<String, String> params) {
        try {
//            Map<String, Object> params = this.getPage().getParams();
            map.put("act_id", params.get("act_id"));
            //查询厂商下拉列表
            map.put("manufacturer", manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null));
            //查询激活返现配置的机具类型以及其返现金额
            map.put("actTerminalModel", actActiveService.getActTerminalModelDetail(params));
            //查询交易达标返现
            List<Map<String, Object>> actTransactionCompliance = iActTransactionComplianceService.getActTransactionCompliance(params);

            for (Map<String, Object> item : actTransactionCompliance) {
                item.put("stage_id", item.get("STAGE_ID"));
                item.put("stage", iActStageService.getActStage(item));
                Map<String, Object> ruleMap = Maps.newHashMap();
                ruleMap.put("ruleid", "transactionreturn" + item.get("ID"));
                List<Map<String, Object>> paymentType = iActPaymentTypeService.getActPaymentType(ruleMap);
                item.put("paymentType", paymentType);
                //查询活动中采购人奖励
                item.put("buyMoney",actActiveService.selectActActiveById(params.get("act_id")).getBuyMoney());
                item.put("pos_type",actActiveService.selectActActiveById(params.get("act_id")).getPosType());
                String ylId = actActiveService.selectActActiveById(params.get("act_id")).getProYlId();
                String agentNum = actActiveService.selectActActiveById(params.get("act_id")).getAgentNum();
                String ylName = actActiveService.selectActActiveById(params.get("act_id")).getProYlName();
                String ylIdName = ylName != null ? ylId + "-" +ylName : "";
                item.put("ylIdName",ylIdName);
                item.put("ylId",ylId);
                item.put("agentNum",agentNum);
            }
            ActActive actActive = actActiveService.selectActActiveById(params.get("act_id"));
            map.put("act", actActive);


            Map wjh = actActiveService.selectWjh(params.get("act_id"),"0");
            map.put("wjh", wjh);

            Map wjh1 = actActiveService.selectWjh(params.get("act_id"),"1");
            map.put("wjh1", wjh1);

            map.put("actTransactionCompliance", actTransactionCompliance);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("活动信息有误");
        }
        return prefix + "/dbfx";
    }

    /**
     * 查询活动配置列表
     */
    @PostMapping("/actList")
    @ResponseBody
    public TableDataInfo actList(ActActive actActive)
    {
        startPage();
        List<ActActive> list = actActiveService.getActByAgent(actActive);
        return getDataTable(list);
    }
    @PostMapping("/actLists")
    @ResponseBody
    public TableDataInfo actLists(ActActive actActive)
    {
        startPage();
        List<ActActive> list = actActiveService.selectActActiveList(actActive);
        return getDataTable(list);
    }

    @RequestMapping("/addActReturnMoney")
    @ResponseBody
    public AjaxResult addActReturnMoney(@RequestParam("act_id") String actId, @RequestParam("data")String data) {
        int result = actActiveService.addActReturnMoney(actId, data);
        if(result == 120){
            return AjaxResult.error("输入金额有误,采购人奖励与达标返现金额之和不得超过120元！");
        }else if (result == 200){
            return AjaxResult.error("输入金额有误,采购人奖励与达标返现金额之和不得超过200元！");
        }else if (result < 1){
            return AjaxResult.error("保存失败！");
        }else{
            return AjaxResult.success("保存成功！");
        }
    }


    /**
     * 修改活动配置
     */
    @GetMapping("/activeView")
    public String activeView() {
        return prefix + "/activeView";
    }


    /**
     * 获取达标返现数据
     * @Param []
     * @Return com.hjm.framework.web.page.TableDataInfo
     */
    @RequestMapping("/getLists")
    @ResponseBody
    public TableDataInfo getLists(){
        List<Map<String, String>> actList = actActiveService.getLists("100000000");
        return getDataTable(actList);
    }
}
